package com.edu.neusoft.elec_shop.controller;

import com.edu.neusoft.elec_shop.domain.ShoppingCart;
import com.edu.neusoft.elec_shop.service.ShoppingCartService;
import com.edu.neusoft.elec_shop.util.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
@Api(tags = "购物车管理接口")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    // 用户向购物车内添加商品
    @PostMapping
    @ApiOperation(value = "添加商品到购物车", notes = "接收购物车商品对象作为请求体，将商品添加到购物车中")
    public AjaxResult addToShoppingCart(@RequestBody @Valid ShoppingCart shoppingCart) {
        try {
            int result = shoppingCartService.addToShoppingCart(shoppingCart);
            if (result > 0) {
                return AjaxResult.success("商品添加到购物车成功");
            } else {
                return AjaxResult.error("商品添加到购物车失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("商品添加到购物车失败：" + e.getMessage());
        }
    }

    // 用户将商品从购物车移除
    @DeleteMapping("/{cartId}")
    @ApiOperation(value = "从购物车移除商品", notes = "根据传入的购物车商品ID，将对应的商品从购物车中移除")
    public AjaxResult deleteByGoodsId(@PathVariable("cartId") Long cartId) {
        try {
            int result = shoppingCartService.deleteByGoodsId(cartId);
            if (result > 0) {
                return AjaxResult.success("商品从购物车移除成功");
            } else {
                return AjaxResult.error("商品从购物车移除失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("商品从购物车移除失败：" + e.getMessage());
        }
    }

    // 查看购物车内所有商品信息
    @GetMapping("/{userId}")
    @ApiOperation(value = "根据用户ID查看购物车信息", notes = "根据传入的用户ID，获取该用户购物车内的所有商品信息")
    public AjaxResult getShoppingCartByUserId(@PathVariable("userId") Long userId) {
        try {
            List<ShoppingCart> shoppingCarts = shoppingCartService.getShoppingCartByUserId(userId);
            return AjaxResult.success("获取购物车信息成功", shoppingCarts);
        } catch (Exception e) {
            return AjaxResult.error("获取购物车信息失败：" + e.getMessage());
        }
    }
}